import os
import json
import subprocess
from datetime import datetime

# 常量定义
def get_game_name(platform: str) -> str:
    # 根据平台类型获取游戏名称
    return "EasyAdventure"  # 默认值

CREATOR_PATH = r"C:\ProgramData\cocos\editors\Creator\2.4.10\CocosCreator.exe"
WEB_PUB_PATH = os.path.join("E:\\", "CCWebGame", "public", "EmotionalHealing", "web-mobile")
LOCAL_DOMAIN = "http://20.0.0.58:3000"
PROD_DOMAIN = "https://fish2.ckbuyu.com"

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--ttlocal', action='store_true', help='Build for bytedance local debug mode')
    parser.add_argument('--tt', action='store_true', help='Build for bytedance production mode')
    parser.add_argument('--web', action='store_true', help='Build for web platform')
    parser.add_argument('--kslocal', action='store_true', help='Build for kuaishou local debug mode')
    parser.add_argument('--ks', action='store_true', help='Build for kuaishou production mode')
    parser.add_argument('--migulocal', action='store_true', help='Build for migu local debug mode')
    parser.add_argument('--migu', action='store_true', help='Build for migu production mode')
    args = parser.parse_args()

    # 平台配置映射
    platform_configs = {
        "web": {"name": "网页项目", "platform": "web-mobile", "debug": "false", "domain": "", "pub_path": WEB_PUB_PATH},
        "ttlocal": {"name": "抖音本地调试项目", "platform": "bytedance", "debug": "true", "domain": LOCAL_DOMAIN},
        "tt": {"name": "抖音正式项目", "platform": "bytedance", "debug": "false", "domain": PROD_DOMAIN},
        "kslocal": {"name": "快手本地调试项目", "platform": "wechatgame", "debug": "true", "domain": LOCAL_DOMAIN},
        "ks": {"name": "快手正式项目", "platform": "wechatgame", "debug": "false", "domain": PROD_DOMAIN},
        "migulocal": {"name": "咪咕本地调试项目", "platform": "migu-runtime", "debug": "true", "domain": LOCAL_DOMAIN},
        "migu": {"name": "咪咕正式项目", "platform": "migu-runtime", "debug": "false", "domain": PROD_DOMAIN}
    }

    # 获取选中的平台配置
    selected = next((k for k in platform_configs if getattr(args, k)), None)
    if not selected:
        print("错误：必须指定构建模式参数(--web, --tt, --ks, --migu 等)")
        return 1

    config = platform_configs[selected]
    print(f"开始构建{config['name']}")
    platform = config["platform"]
    debug_mode = config["debug"]
    domain = config["domain"]
    pub_path = config.get("pub_path", "")
    
    # 构建部分
    if not args.web:
        file_path = os.path.join(".", "settings", "bytedance.json" if platform == "bytedance" else "wechatgame.json" if platform == "wechatgame" else "migu-runtime.json")
        key = "REMOTE_SERVER_ROOT" if platform != "migu-runtime" else "tinyPackageServer"
        
        now = datetime.now()
        curr_date = now.strftime("%Y%m%d")
        curr_time = now.strftime("%H%M")
        
        game_name = get_game_name(platform)
        server_url = f"{domain}/{game_name}/{curr_date}{curr_time}/"
        
        # 修改JSON文件
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            data[key] = server_url
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"JSON修改失败: {e}")
            return 1
        
        print(f"CDN地址: {server_url}")
    
    # 执行构建命令
    build_cmd = f"{CREATOR_PATH} --path ./ --build \"platform={platform};debug={debug_mode};md5Cache=true\""
    try:
        subprocess.run(build_cmd, shell=True, check=True)
        print("构建完成")
    except subprocess.CalledProcessError as e:
        print(f"构建失败: {e}")
        return 1
    
    # 发布更新
    print("准备发布更新")
    
    # 获取构建和发布路径
    if args.web:
        upd_path = os.path.join(os.getcwd(), "build", "web-mobile")
        pub_path = WEB_PUB_PATH
    else:
        game_name = get_game_name(platform)
        pub_path = os.path.join("E:\\", "CCWebGame", "public", game_name, f"{curr_date}{curr_time}", "remote")
        upd_path = os.path.join(os.getcwd(), "build", platform, "remote")
    
    # 处理发布更新
    if not handle_publish(upd_path, pub_path, args.web):
        return 1
    
    if not args.web:
        print(f"CDN地址: {server_url}")
    
    # 咪咕平台需要处理rpk文件
    if args.migulocal or args.migu:
        print("正在处理rpk文件")
        if not handle_rpk_file(args.migulocal):
            return 1
    
    print("全部完成")
    return 0

def handle_publish(upd_path: str, pub_path: str, is_web: bool) -> bool:
    # 处理发布更新
    if not os.path.exists(upd_path):
        print(f"构建目录不存在: {upd_path}")
        return False
    
    try:
        # 确保父目录存在
        parent_dir = os.path.dirname(pub_path)
        if parent_dir and not os.path.exists(parent_dir):
            os.makedirs(parent_dir, exist_ok=True)
            
        if is_web:
            if os.path.exists(pub_path):
                subprocess.run(f"rd /Q/S {pub_path}", shell=True, check=True)
        
        os.makedirs(pub_path, exist_ok=True)
        subprocess.run(f"xcopy {upd_path} {pub_path} /E/Q", shell=True, check=True)
        
        if not is_web:
            if os.path.exists(upd_path):
                subprocess.run(f"rd /Q/S {upd_path}", shell=True, check=True)
                
        print("服务器更新完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"发布更新失败: {e}")
        return False
    except Exception as e:
        print(f"发布更新发生意外错误: {e}")
        return False

def handle_rpk_file(is_local: bool) -> bool:
    # 处理rpk文件
    rpk_path = os.path.join(os.getcwd(), "build", "migu-runtime", "dist", "H5ChildGodRoad.rpk")
    new_rpk_path = os.path.join(os.getcwd(), "build", "migu-runtime", "dist", "com.上海元游网络科技有限公司.少年仙路.miguminigame.rpk")
    
    if not os.path.exists(rpk_path):
        print(f"未找到源文件: {rpk_path}")
        return False
    
    try:
        if is_local:
            subprocess.run(f'copy "{rpk_path}" "{new_rpk_path}"', shell=True, check=True)
            print("复制完成")
        else:
            os.rename(rpk_path, new_rpk_path)
            print("重命名完成")
        return True
    except (subprocess.CalledProcessError, OSError) as e:
        print(f"处理rpk文件失败: {e}")
        return False

if __name__ == "__main__":
    main()